﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using H2.NET.Common;
using H2.NET.Web.Workflow.DwzCode;
using H2.NET.Web.Workflow.Helper;
using log4net;
using Ultimus.OC;
using Ultimus.WFServer;
using UServLib;
using H2.NET.Business.Core;
using H2.NET.Data.Common;
using System.Text;
using System.Data.SqlClient;
using H2.NET.DBUtility;

namespace H2.NET.Web.Workflow.Workflow
{
    public partial class RedirectStep : BasePage
    {
        /// <summary>
        /// 日志记录
        /// </summary>
        private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public List<Task> CurrentSteps = new List<Task>();
        
        protected void Page_Load(object sender, EventArgs e)
        {
            var action = AksRequest.GetQueryStringValue("action");
            if (string.IsNullOrEmpty(action)) //默认页面加载
            {
                var processName = AksRequest.GetString("process").Trim();
                var incidentNo = AksRequest.GetInt("incident", 0);

                hidProcess.Value = processName;
                hidIncident.Value = incidentNo.ToString();

                var taskList = new Tasklist();
                taskList.LoadFilteredTasks(new TasklistFilter
                {
                    strProcessNameFilter = processName,
                    nIncidentNo = incidentNo,
                    nFiltersMask = Filters.nFilter_Current
                });
                
                //找出当前流程的当前步骤
                for (var i = 0; i < taskList.GetTasksCount(); i++)
                {
                    CurrentSteps.Add(taskList.GetAt(i));
                }

                taskList.LoadFilteredTasks(new TasklistFilter
                {
                    strProcessNameFilter = processName,
                    nIncidentNo = incidentNo,
                    nFiltersMask = Filters.nFilter_Urgent
                });
                for (var i = 0; i < taskList.GetTasksCount(); i++)
                {
                    var tsk = taskList.GetAt(i);
                    if (CurrentSteps.All(t => t.strTaskId != tsk.strTaskId))
                    {
                        CurrentSteps.Add(tsk);
                    }
                }

                taskList.LoadFilteredTasks(new TasklistFilter
                {
                    strProcessNameFilter = processName,
                    nIncidentNo = incidentNo,
                    nFiltersMask = Filters.nFilter_Overdue
                });
                for (var i = 0; i < taskList.GetTasksCount(); i++)
                {
                    var tsk = taskList.GetAt(i);
                    if (CurrentSteps.All(t => t.strTaskId != tsk.strTaskId))
                    {
                        CurrentSteps.Add(tsk);
                    }
                }
                
                //加载实例信息
                var incident = new Incident();
                incident.LoadIncident(processName, incidentNo);
                
                rptAllSteps.DataSource = incident.GetProcessStepLabels(); ;
                rptAllSteps.DataBind();

            }
            else if (action == "save") //form提交
            {
                var flagClose = true;
                var flagRedirect = false;

                var processName = AksRequest.GetString("hidProcess").Trim();
                var incidentNo = AksRequest.GetInt("hidIncident", 0);
                var closeAction = AksRequest.GetString("closeAction");

                try
                {
                    //加载实例信息
                    var incident = new Incident();
                    incident.LoadIncident(processName, incidentNo);

                    //关闭步骤
                    var abortSteps = AksRequest.GetString("abortSteps");
                    var aryAbortSteps = abortSteps.Split(',');

                    foreach (var step in aryAbortSteps)
                    {
                        if (string.IsNullOrEmpty(step)) continue;

                        var ary = step.Split('^');
                        var stepLabel = ary[0];
                        var stepUser = ary[1];

                        switch (closeAction)
                        {
                            case "abort":
                                flagClose = incident.AbortStep(stepLabel);
                                break;
                            case "send":
                                var filter = new TasklistFilter
                                {
                                    strProcessNameFilter = processName,
                                    nIncidentNo = incidentNo,
                                    strStepLabelFilter = stepLabel,
                                    strArrUserName = new string[1] { stepUser }
                                };

                                var taskList = new Tasklist();
                                taskList.LoadFilteredTasks(filter);
                                var task = taskList.GetFirstTask();
                                if (task == null) continue;

                                var strError = "";
                                var n = 0;
                                Variable[] variables;
                                task.GetAllTaskVariables(out variables, out strError);
                                flagClose = task.SendFrom(stepUser, variables, "流程干预手动Send by" + UserAPI.UserFullName,
                                    task.strSummary, ref n, out strError);

                                break;

                            case "close":
                                var strSql = new StringBuilder();
                                strSql.Append("UPDATE TASKS SET STATUS=3 ");
                                strSql.Append(
                                    "WHERE PROCESSNAME=@Process AND INCIDENT=@Incident AND STEPLABEL=@Step AND TASKUSER=@User");
                                SqlParameter[] parameters =
                                {
                                    new SqlParameter("@Process", SqlDbType.VarChar, 50),
                                    new SqlParameter("@Incident", SqlDbType.Int, 4),
                                    new SqlParameter("@Step", SqlDbType.VarChar, 50),
                                    new SqlParameter("@User", SqlDbType.VarChar, 50)
                                };
                                parameters[0].Value = processName;
                                parameters[1].Value = incidentNo;
                                parameters[2].Value = stepLabel;
                                parameters[3].Value = stepUser;

                                DbHelperSQL.connectionString = PubConstant.GetConnectionString("bpmDB");
                                int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
                                flagClose = rows > 0;
                                break;
                        }
                    }

                    //激活步骤
                    var directStep = AksRequest.GetFormString("RedirectStep");
                    if (!string.IsNullOrEmpty(directStep))
                    {
                        flagRedirect = incident.DirectActivateStep(directStep);
                    }

                    var incidentManageLog = new t_log_IncidentManage
                    {
                        Process = processName,
                        Incident = incidentNo,
                        Status = flagClose || flagRedirect,
                        Action = "激活或关闭步骤",
                        Description =
                            (string.IsNullOrEmpty(directStep) ? "" : "激活步骤" + directStep) +
                            (aryAbortSteps.Length > 0 ? "关闭步骤" + abortSteps : ""),
                        Creator = UserAPI.UserFullName,
                        CreateOn = DateTime.Now
                    };
                    Storage.Save(incidentManageLog);

                }
                catch (Exception ex)
                {
                    // 记录错误日志
                    var errorLog = new t_log_IncidentManage
                    {
                        Process = processName,
                        Status = false,
                        Action = "激活或关闭步骤",
                        Description = "ERROR:" + ex.Message,
                        Creator = UserAPI.UserFullName,
                        Incident = incidentNo,
                        CreateOn = DateTime.Now
                    };
                    Storage.Save(errorLog);

                    Logger.Error(ex.Message);
                    ErrorMsg(ex.Message);
                }


                if (flagClose || flagRedirect)
                {
                    SuccessMsg();
                }
                else
                {
                    ErrorMsg("操作失败");
                }
            }
        }


    }
}